//
// Created by 86137 on 2024/3/16.
//

#include "task_bluetooth.h"
rc_blue_t blue_rc;
extern osSemaphoreId_t buletoothBinarySemHandle;
uint32_t blue_error_cnt=0;
uint32_t blue_lost_cnt=0;


void blueToothTask(void *argument){
    static osStatus_t stat;
    rc_blue_init(&blue_rc,&RC_UART_blue,blue_update_callback);
    HAL_UART_RegisterCallback(blue_rc._huart, HAL_UART_ERROR_CB_ID, blue_unlink_restart);
    osSemaphoreAcquire(buletoothBinarySemHandle, 0);

    for (;;) {
        blue_start_receive_dma(&blue_rc);
        stat = osSemaphoreAcquire(buletoothBinarySemHandle, 15);
        //在HAL_UART_RegisterRxEventCallback中释放
        if (stat == osOK) {
            if (blue_update(&blue_rc)) {
                set_blue_connect(&blue_rc);
            }
        }
        else {
            set_blue_lost(&blue_rc);
            blue_lost_cnt++;
        }
    }
}

void rc_blue_init(rc_blue_t * rc_blue, UART_HandleTypeDef *_huart, pUART_RxEventCallbackTypeDef rc_pCallback){
    rc_blue->is_lost_blue = true;//保证不发送数据
    rc_blue->_huart = _huart;
    HAL_UART_RegisterRxEventCallback(blue_rc._huart, rc_pCallback);
}

void blue_update_callback(UART_HandleTypeDef *huart, uint16_t Size) {
    osSemaphoreRelease(buletoothBinarySemHandle);


}
void blue_unlink_restart(UART_HandleTypeDef *huart) {
    //HAL_DMA_Init(huart->hdmarx);
    blue_error_cnt++;
}


void blue_start_receive_dma(rc_blue_t * rc_blue){
    HAL_UARTEx_ReceiveToIdle_DMA(rc_blue->_huart, (uint8_t *)&rc_blue->raw_blue_data, BLUE_BUFF_LEN);//封装好的函数
    __HAL_DMA_DISABLE_IT(rc_blue->_huart->hdmarx, DMA_IT_HT);//关闭半满中断
    //__HAL_DMA_DISABLE_IT(rc_dev->_huart->hdmarx,DMA_IT_TC);//关闭全满中断
}
//总函数
bool blue_update(rc_blue_t * rc_blue) {
    blue_update_(rc_blue, &rc_blue->raw_blue_data);
    return true;
}
void blue_update_(rc_blue_t * rc_blue, uint8_t *buff) {
    memcpy(&rc_blue->last_blue_data, &rc_blue->blue_data, sizeof(rc_blue->blue_data));
    blue_data_update(rc_blue->blue_data, rc_blue->raw_blue_data);
}

void blue_data_update(uint8_t blue_data, uint8_t buff){
    blue_data = buff;
}
void set_blue_connect(rc_blue_t * rc_blue){
    rc_blue->is_lost_blue = false;
}
void set_blue_lost(rc_blue_t * rc_blue){
    rc_blue->is_lost_blue = true;
}
